﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ServerMonitor
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //try
            //{ 
            //    Application.EnableVisualStyles(); 
            //    Application.SetCompatibleTextRenderingDefault(false); 
            //    Application.Run(new Form1());
            //}
            //catch (Exception ex) {

            //    Common.LogHelper.WriteLog(ex.Message.ToString(), ex.Source+"Main");
            //}
            bool createNew;
            using (System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out createNew))
            {
                if (createNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1()); 
                }
                else
                {
                    string pName = Application.ProductName;
                    string pPath = Application.ExecutablePath;
                    List<Process> temp = Process.GetProcessesByName(pName).ToList();//在所有已启动的进程中查找需要的进程； 
                    if (temp.Count > 0)//如果查找到
                    {
                        foreach (var pro in temp)
                        {
                            if (pro.ProcessName.Equals(pName) && pro.MainModule.FileName.Equals(pPath))
                            {
                                IntPtr handle = pro.MainWindowHandle;
                                SwitchToThisWindow(handle, true); // 激活，显示在最前   
                            }
                        }
                    }
                    // MessageBox.Show("Only one instance of this application is allowed!");
                }

            }
        } 

        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
    }
}